package com.flying.um.domain.service;

import com.flying.um.model.QUser;
import com.flying.um.model.User;
import com.flying.um.model.jdbc.UserRepository;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;

@Service
public class UserService {
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private UserRepository userRepository;

    private JPAQueryFactory queryFactory;

    @PostConstruct
    public void initFactory() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public User findByName(String username) {
        QUser qUser = QUser.user;
        return queryFactory.select(qUser).from(qUser)
                .where(qUser.username.eq(username))
                .join(qUser.roles).fetchJoin().fetchOne();
    }
}